// ScheduleConfig.java
package com.xiaoxu.intranetweb.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
@EnableScheduling
@Slf4j
public class ScheduleConfig implements SchedulingConfigurer, AsyncConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleConfig.class);

    // 根据CPU核心数动态设置线程池大小
    private static final int CPU_CORES = Runtime.getRuntime().availableProcessors();

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();

        // 基础配置
        taskScheduler.setPoolSize(5); // 推荐5-10之间
        taskScheduler.setThreadNamePrefix("eam-upload-");
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.setAwaitTerminationSeconds(60);
        taskScheduler.setRemoveOnCancelPolicy(true);

        // 错误处理
        taskScheduler.setErrorHandler(t -> {
            log.error("定时任务执行异常", t);
            // 可以添加告警通知
        });

        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

    @Bean(name = "videoTaskScheduler")
    public TaskScheduler videoTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(CPU_CORES * 4);  // IO密集型任务
        scheduler.setThreadNamePrefix("video-scheduler-");
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        scheduler.initialize();
        return scheduler;
    }
    // 添加上传专用线程池
    @Bean(name = "uploadTaskExecutor")
    public Executor uploadTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(30);
        executor.setThreadNamePrefix("upload-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    @Bean(name = "ioExecutor")
    public Executor ioExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CPU_CORES * 8);
        executor.setMaxPoolSize(CPU_CORES * 16);
        executor.setQueueCapacity(1000);
        executor.setKeepAliveSeconds(30);
        executor.setThreadNamePrefix("io-worker-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public Executor getAsyncExecutor() {
        return ioExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new VideoAsyncExceptionHandler();
    }

    private static class VideoAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            logger.error("视频处理异常 [方法: {} 参数: {}]：{}",
                    method.getName(),
                    Arrays.toString(params),
                    ex.getMessage());

            // 自动清理临时文件
            if (params.length > 0 && params[0] instanceof Path) {
                Path original = (Path) params[0];
                cleanupTempFiles(original);
            }
        }

        private void cleanupTempFiles(Path original) {
            try {
                Files.deleteIfExists(original.resolveSibling(original.getFileName() + ".tmp"));
                Files.deleteIfExists(original.resolveSibling(original.getFileName() + ".lock"));
                Files.deleteIfExists(original.resolveSibling(original.getFileName() + ".bak"));
            } catch (IOException e) {
                logger.warn("临时文件清理失败: {}", e.getMessage());
            }
        }
    }
}